package com.li.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.li.client.DataService;
import com.li.client.entities.BookInfo;
import com.li.client.entities.BookType;
import com.li.client.entities.Publisher;
import com.li.client.entities.User;

public class DataServiceImpl extends BaseGwtServiceServlet implements DataService {
	private BookService bookService = new BookServiceImpl();
	private UserService userService = new UserServiceImpl();
	private PubliserService publiserService = new PubliserServiceImpl();
	private BookTypeService bookTypeServiceImpl = new BookTypeServiceImpl();
	
	private static Map<String, Publisher> pulisherMap = new HashMap<String, Publisher>();
	private static Map<String, BookType> typeMap = new HashMap<String, BookType>();
	@Override
	public User getCurrentUser() {
		
		return new User();
	}

	@Override
	public List<BookInfo> getAllBookInfo() {
		return bookService.getAllBookInfo();
	}

	@Override
	public Boolean borrowBook(String userId, String isbnCode) {
		return bookService.borrowBook(userId, isbnCode);
	}

	@Override
	public BookInfo getBookByISBN(String isbnCode) {
		return bookService.getBookByISBN(isbnCode);
	}

	@Override
	public User getUserByUserId(String userId) {
		return userService.getUserByUserId(userId);
	}

	@Override
	public Boolean returnBook(Integer pkUserId, Integer pkBookId) {
		return bookService.returnBook(pkUserId, pkBookId);
	}

	@Override
	public Integer getBookInStock(String isbnCode) {
		return bookService.getBookInStock(isbnCode);
	}

	@Override
	public User loginSystem(String loginId, String pwd) {
		return userService.loginSystem(loginId, pwd);
	}

	protected FileItemStream getUploadedFile(HttpServletRequest request) throws Exception
	{
		FileItemStream item = null;
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		FileItemIterator iter = upload.getItemIterator(request);
		FileItemStream fileItem = null;
		while (iter.hasNext())
		{
			fileItem = iter.next();
			if (!fileItem.isFormField())
			{
				item = fileItem;
				break;
			}
		}
		return item;

	}
	
	private String getFileName(FileItemStream item)
	{
		String fileName = null;
		String completeFileName = null;
		completeFileName = new File(item.getName()).getName();
		int endIndex = completeFileName.indexOf(".");
		fileName = completeFileName.substring(0, endIndex);

		return completeFileName;
	}
	
	
	@Override
	protected void processNonGwtDataService(String dataServiceType,
			HttpServletRequest request, HttpServletResponse resp)
			throws IOException {
		if ("fileUpload".equals(dataServiceType)) {
//			FileItemStream item = null;
//			try
//			{
//				item = getUploadedFile(request);
//			}
//			catch (Exception e)
//			{
//			}
//			
//			File uploadedFile = new File("csv");
//			String path = uploadedFile.getAbsolutePath();
//			String pathDirAndName = path + File.separator + getFileName(item);
//			
//			File saveFile = new File(pathDirAndName);
//			InputStream openStream = null;
//			FileOutputStream output = null;
//			try
//			{
//				openStream = item.openStream();
//				
//				output = FileUtils.openOutputStream(saveFile);
//				IOUtils.copy(openStream, output);
//			}
//			finally
//			{
//				IOUtils.closeQuietly(output);
//			}
//			
//			processEnrollment(pathDirAndName);
			
			PrintWriter writer = null;
			
			try {
				resp.setContentType("text/plain");
				writer = resp.getWriter();
				
				writer.print("[BEGIN]TRUE[END]");
				
				
			} catch (Exception e) {
			} finally {
				writer.flush();
				writer.close();
			}
		}
	}
	
	private Publisher getPublisherFromMap(String pName) {
		Publisher p = pulisherMap.get(pName.trim());
		if (p == null) {
			List<Publisher> allPublisher = publiserService.getAllPublisher();
			for (Publisher pu : allPublisher) {
				pulisherMap.put(pu.getName(), pu);
			}
			p = pulisherMap.get(pName.trim());
		}
		return p;
	}
	
	private BookType getTypeFromMap(String name) {
		BookType bt = typeMap.get(name.trim());
		if (bt == null) {
			List<BookType> allBookType = bookTypeServiceImpl.getAllBookType();
			for (BookType bookType : allBookType) {
				typeMap.put(bookType.getTypeName(), bookType);
			}
			bt = typeMap.get(name.trim());
		}
		return bt;
	}
	
	public void processEnrollment(String path) {
		InputStream in = null;
		try {
			File file = new File(path);
			in = new FileInputStream(file);
			Workbook wb = WorkbookFactory.create(in);
			Sheet sheet = wb.getSheetAt(0);
			Iterator<Row> rowIterator = sheet.rowIterator();
			rowIterator.next();
			
			List<BookInfo> bookList = new ArrayList<BookInfo>();
			
			while(rowIterator.hasNext()) {
				BookInfo bi = new BookInfo();
				
				Row r = rowIterator.next();
				bi.setBookName(r.getCell(0).getStringCellValue());
				bi.setIsbnCode(r.getCell(1).getStringCellValue());
				bi.setBookPrice(new BigDecimal(r.getCell(2).getNumericCellValue()));
				bi.setPublisher(getPublisherFromMap(r.getCell(3).getStringCellValue()));
				bi.setBookType(getTypeFromMap(r.getCell(4).getStringCellValue()));
				
				bookList.add(bi);
			}
			
			bookService.batchInsert(bookList);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
		
		
	}

}
